<template>
  <div class="page-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>个人资料</span>
        </div>
      </template>
      <div class="content-wrapper">
        <el-row :gutter="20" class="content-row">
          <!-- 左侧头像 -->
          <el-col :xs="24" :sm="6" class="avatar-col">
            <el-form-item>
              <el-upload
                :action="uploadUrl"
                :on-success="handleUploadSuccess"
                :show-file-list="false"
                accept="image/*"
                class="avatar-uploader"
              >
                <el-avatar :src="form.avatarUrl || defaultAvatar" :size="120" class="avatar" />
                <template #tip>
                  <div class="el-upload__tip">点击头像上传（JPG/PNG，最大 2MB）</div>
                </template>
              </el-upload>
            </el-form-item>
          </el-col>
          <!-- 右侧表单 -->
          <el-col :xs="24" :sm="18" class="form-col">
            <el-form :model="form" :rules="rules" ref="userForm" label-width="120px" class="user-form">
              <el-row :gutter="20">
                <el-col :xs="24" :sm="12">
                  <el-form-item label="用户名" prop="username">
                    <el-input v-model="form.username" disabled class="custom-input" />
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12">
                  <el-form-item label="手机号" prop="mobile">
                    <el-input v-model="form.mobile" placeholder="请输入手机号" class="custom-input" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :xs="24" :sm="12">
                  <el-form-item label="邮箱" prop="email">
                    <el-input v-model="form.email" placeholder="请输入邮箱" class="custom-input" />
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12">
                  <el-form-item label="真实姓名" prop="realName">
                    <el-input v-model="form.realName" placeholder="请输入真实姓名" class="custom-input" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :xs="24" :sm="12">
                  <el-form-item label="性别" prop="gender">
                    <el-select v-model="form.gender" placeholder="请选择性别" class="custom-select">
                      <el-option label="男" value="male" />
                      <el-option label="女" value="female" />
                      <el-option label="未知" value="unknown" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12">
                  <el-form-item label="出生日期" prop="birthday">
                    <el-date-picker
                      v-model="form.birthday"
                      type="date"
                      placeholder="选择出生日期"
                      format="YYYY-MM-DD"
                      value-format="YYYY-MM-DD"
                      class="custom-date-picker"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="24">
                  <el-form-item label="收货地址" prop="address">
                    <el-input v-model="form.address" placeholder="请输入收货地址" class="custom-input" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-form-item class="submit-button">
                <el-button type="primary" @click="handleSubmit" :loading="submitting">保存</el-button>
              </el-form-item>
            </el-form>
          </el-col>
        </el-row>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { useUserInfoStore } from '@/stores/userInfo'
import { userInfoService, updateUserInfoService } from '@/api/user'
import defaultAvatar from '@/assets/default.png'

const userInfoStore = useUserInfoStore()
const userForm = ref(null)
const submitting = ref(false)
const loading = ref(false) // 新增加载状态
const baseUrl = 'http://localhost:8080'
const uploadUrl = '/api/upload/avatar'

// 确保所有字段都有初始值
const form = reactive({
  id: null,
  username: '',
  mobile: '',
  email: '',
  realName: '',
  gender: '',
  address: '',
  birthday: '',
  avatarUrl: ''
})

const rules = {
  mobile: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  realName: [{ required: true, message: '请输入真实姓名', trigger: 'blur' }],
  address: [{ required: true, message: '请输入收货地址', trigger: 'blur' }]
}

const fetchUserInfo = async () => {
  loading.value = true
  try {
    const res = await userInfoService(userInfoStore.userInfo.id)
    console.log('API完整响应:', res) // 打印完整响应
    
    // 检查数据结构
    const userData = res.data?.data || res.data
    
    if (!userData) {
      throw new Error('用户数据格式不正确')
    }
    
    // 逐个赋值确保响应式更新
    Object.keys(userData).forEach(key => {
      if (key in form) {
        form[key] = userData[key]
      }
    })
    
    userInfoStore.updateUserInfo(userData)
  } catch (error) {
    console.error('获取用户信息失败:', error)
    ElMessage.error('获取用户信息失败: ' + error.message)
  } finally {
    loading.value = false
  }
}

const handleSubmit = async () => {
  submitting.value = true
  try {
    await userForm.value.validate()
    
    // 确保包含必要字段
    const submitData = {
      ...form,
      id: userInfoStore.userInfo.id // 确保包含ID
    }
    
    console.log('提交的数据:', submitData) // 调试用
    
    const res = await updateUserInfoService(submitData)
    localStorage.setItem('userInfo', JSON.stringify({
            avatar: submitData.avatarUrl
          }))
    console.log('更新响应:', res) // 调试用
    
    if (res.status == 200 ) {
      ElMessage.success('更新成功')
      userInfoStore.updateUserInfo(form)
    } else {
      ElMessage.error(res.message || '更新失败，未知错误')
    }
  } catch (error) {
    console.error('更新错误详情:', error)
    let errorMsg = '更新失败'
    if (error.response) {
      // 尝试获取更详细的错误信息
      errorMsg = error.response.data?.message || 
                 error.response.data?.error || 
                 error.response.statusText
    }
    ElMessage.error(`${errorMsg} (${error.message})`)
  } finally {
    submitting.value = false
  }
}

const handleUploadSuccess = (response) => {
  if (response.url) {
    form.avatarUrl = response.url.startsWith('http') ? response.url : `${baseUrl}${response.url}`
    
    ElMessage.success('头像上传成功')
  } else {
    ElMessage.error('头像上传失败: ' + (response.message || '未知错误'))
  }
}

onMounted(() => {
  fetchUserInfo()
})
</script>


<style lang="scss" scoped>
.page-container {
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  padding: 0;
}

.box-card {
  width: 100%; /* 占满父容器宽度 */
  height: 100%;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  background: #ffffff;
  display: flex;
  flex-direction: column;
}

.card-header {
  font-size: 20px;
  font-weight: 700;
  color: #303133;
  padding: 16px 20px;
  border-bottom: 1px solid #e4e7ed;
  background: #fafafa;
}

.content-wrapper {
  flex: 1;
  padding: 16px;
  display: flex;
  align-items: center;
}

.content-row {
  width: 100%;
  height: 100%;
}

.avatar-col {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
}

.user-form {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.el-row {
  margin-bottom: 12px;
}

.el-form-item {
  margin-bottom: 16px;
}

.custom-input,
.custom-select,
.custom-date-picker {
  .el-input__inner,
  .el-select__input,
  .el-date-editor {
    border-radius: 8px;
    transition: all 0.3s;
    &:hover {
      border-color: #409eff;
    }
    &:focus {
      border-color: #409eff;
      box-shadow: 0 0 5px rgba(64, 158, 255, 0.5);
    }
  }
}

.avatar-uploader {
  text-align: center;
  .el-avatar {
    border: 2px solid #e4e7ed;
    border-radius: 50%;
    transition: transform 0.3s, border-color 0.3s;
    &:hover {
      transform: scale(1.1);
      border-color: #409eff;
    }
  }
  .el-upload__tip {
    margin-top: 12px;
    color: #606266;
    font-size: 14px;
  }
}

.submit-button {
  text-align: center;
  margin-top: auto;
  .el-button {
    padding: 12px 40px;
    border-radius: 8px;
    font-size: 16px;
    transition: all 0.3s;
    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
    }
  }
}

/* 响应式调整 */
@media (max-width: 768px) {
  .box-card {
    width: 100%; /* 小屏幕占满 */
  }
  .content-wrapper {
    padding: 12px;
  }
  .avatar-col {
    margin-bottom: 16px;
  }
  .form-col {
    height: auto;
  }
  .user-form {
    justify-content: flex-start;
  }
  .el-row {
    margin-bottom: 10px;
  }
  .el-form-item {
    margin-bottom: 14px;
  }
}
</style>